import Request from 'luch-request'
import { BASE_URL, WHITE_LIST } from './constant'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 实例化网络请求
const request = new Request({
    baseURL:BASE_URL,
    custom:{
        loading:true
    }
})

// 配置请求拦截器
request.interceptors.request.use(
    (config) => {
        console.log(config.url);
        
        if(userStore.token&&!WHITE_LIST.includes(config.url as string)){
            config.header!.Authorization = `Bearer ${userStore.token}`
        }
        uni.showLoading({
            title:'加载中',
            mask:true
        })
        return config
    }, (error) => {
        return Promise.reject(error)
    }
)

// 配置响应拦截器
request.interceptors.response.use(
    (res)=>{
        // 关闭弹层
        uni.hideLoading()
        if(res.data.code!==10000){
            uni.showToast({
                title:res.data.message,
                icon:'none'
            })
            return Promise.reject(res.data)
        }
        return res.data?.data
    },
    (error)=>{
        // 关闭弹层
        uni.hideLoading()
        if(error.statusCode === 401){
            uni.reLaunch({url:'/pages/login/index'})
        }
        uni.showToast({
            title:error.data.message,
            icon:'none'
        })
        return Promise.reject(error)
    }
    
)

export { request }